package com.gosophiaigit.contact.busi.service.impl;

import java.util.ArrayList;
import java.util.List;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springside.core.dao.HibernateEntityDao;

import com.gosophia.commons.exception.BusinessException;
import com.gosophia.userManagement.entity.UserAccount;
import com.gosophia.userManagement.entity.UserInfo;
import com.gosophia.userManagement.service.UserManagementService;
import com.gosophiaigit.contact.busi.entity.Contact;
import com.gosophiaigit.contact.busi.entity.ContactGroup;
import com.gosophiaigit.contact.busi.entity.ContactGroupRelation;
import com.gosophiaigit.contact.busi.entity.ContactPartTime;
import com.gosophiaigit.contact.busi.entity.PositionUser;
import com.gosophiaigit.contact.busi.service.IContactGroupService;
import com.gosophiaigit.contact.busi.service.IContactService;

/**
 * 联系人单表的操作实现类
 * 
 * @author zhangdianliang
 * @since 2011-3-29 上午10:00:33
 */
@Service("contactService")
@Transactional
public class ContactServiceImpl implements IContactService {

	@Autowired
	private HibernateEntityDao<?> hibernateEntityDao;
	@Autowired
	private UserManagementService userManagementService;
	@Autowired
	private IContactGroupService contactGroupService;

	/**
	 * 增加联系人
	 * 
	 * @param contact联系人
	 */
	public void addContact(Contact contact, String contactName,
			Long contactGroupId, Long positionId,
			ContactPartTime contactPartTime) {
		if (StringUtils.isNotBlank(contactName)) {
			UserInfo userInfo = new UserInfo();
			Assert.notNull(contact, "联系人不能为空");
			Assert.isNull(contact.getContactId(), "联系人主键必须为空");
			Assert.notNull(contact.getContactType(), "联系人类型不能为空");
			userInfo.setUserName(contactName);
			Long userInfoId = (Long) hibernateEntityDao.getSessionFactory()
					.getCurrentSession().save(userInfo);
			// 保存职位关联信息
			if (contact.getContactType() == Contact.SYSTEM_IN_CONTACT
					&& positionId != null) {
				PositionUser positionUser = new PositionUser();
				positionUser.setPositionId(positionId);
				positionUser.setUserInfoId(userInfoId);
				hibernateEntityDao.save(positionUser);
			}
			// 保存联系人
			contact.setUserInfoId(userInfoId);
			contact.setSpellName(getPinYin(contactName));
			contact.setContactUseFlag(Contact.CONTACT_ENABLE);// 默认启用
			hibernateEntityDao.save(contact);
			// 保存联系人和组关系
			if (contactGroupId != null) {
				ContactGroupRelation cgRelation = new ContactGroupRelation();
				ContactGroup contactGroup = contactGroupService
						.findContactGroupById(contactGroupId);
				cgRelation.setContact(contact);
				cgRelation.setContactGroup(contactGroup);
				hibernateEntityDao.save(cgRelation);
			}
			//保存联系人兼职信息
			if (contact.getContactType() == Contact.SYSTEM_OUT_CONTACT) {
				contactPartTime.setContact(contact);
				hibernateEntityDao.save(contactPartTime);
			}
		}
		if (contact.getContactType() == Contact.SYSTEM_OUT_CONTACT) {
			contactPartTime.setContact(contact);
			hibernateEntityDao.save(contactPartTime);
		}
	}

	/**
	 * 删除联系人，联系人做逻辑删除，联系人账号做物理删除
	 * 
	 * @param contactId联系人ID
	 */
	public void delContact(Long contactId) {
		Contact contact = getContactById(contactId);
		UserInfo userInfo = userManagementService
				.findUserInfoByUserInfoId(contact.getUserInfoId());
		/** 通过用户得到账号 */
		UserAccount userAccount = userInfo.getUserAccount();
		/** 解除用户和账号的关系 */
		userInfo.setUserAccount(null);
		hibernateEntityDao.update(userInfo);
		/** 物理删除账号 */
		if (userAccount != null) {
			userManagementService.removeUserAccount(userAccount
					.getUserAccountId(), userAccount.getVersion());
		}
		/** 逻辑删除联系人 */
		contact.setContactDelFlag(1L);// 已删除标记
		Assert.notNull(contact, "联系人不能为空");
		hibernateEntityDao.update(contact);

	}

	/**
	 * 编辑联系人
	 * 
	 * @param contact联系人实体
	 * @param contact联系人名称
	 */
	public void modifyContact(Contact contact, String contactName,
			ContactPartTime contactPartTime, PositionUser positionUser) {
		if (contact.getContactType() == Contact.SYSTEM_OUT_CONTACT) {
			contactPartTime.setContact(contact);
			/** 修改联系人的兼职信息 */
			hibernateEntityDao.saveOrUpdate(contactPartTime);
		}
		if (contact.getContactType() == Contact.SYSTEM_IN_CONTACT) {
			/** 修改联系人在系统内的职位 */
			positionUser.setUserInfoId(contact.getUserInfoId());
			Assert.notNull(positionUser, "联系人和职位实体不能为空");
			hibernateEntityDao.saveOrUpdate(positionUser);
		}
		Assert.notNull(contact, "联系人不能为空");
		Assert.notNull(contact.getContactType(), "联系人类型不能为空");
		contact.setSpellName(getPinYin(contactName));
		/** 修改用户名称 */
		String sql = "update T_USERMANA_USERINFO   set USERNAME='"
				+ contactName + "' where USERINFOID=" + contact.getUserInfoId();
		hibernateEntityDao.getSessionFactory().getCurrentSession()
				.createSQLQuery(sql).executeUpdate();
		hibernateEntityDao.update(contact);
	}

	/**
	 * 禁用指定联系人,同时禁用账号
	 * 启用指定联系人
	 * 启用：1，禁用：2
	 */
	@Override
	public Long openOrCloseFlag(Long contactId) {
		Contact contact = getContactById(contactId);
		Long flag = contact.getContactUseFlag();
		if(flag!=null && 1L==flag){//启用变成禁用
			contact.setContactUseFlag(2L);
			hibernateEntityDao.update(contact);
			UserInfo userInfo = userManagementService.findUserInfoByUserInfoId(contact.getUserInfoId());
				if(userInfo!=null){
					UserAccount userAccount = userInfo.getUserAccount();
					if(userAccount!=null){
						try {
							//用户账号启用/禁用状态:true启用；false禁用
							userAccount.setUserAccountIsEnabled(false);
							userManagementService.updateUserAccount(userAccount);
						} catch (BusinessException e) {
							e.printStackTrace();
						}
					}
				}
			return 2L;
		}else{//禁用变成启用
			contact.setContactUseFlag(1L);
			hibernateEntityDao.update(contact);
			return 1L;
		}
	}
	
	/**
	 * 启用账号时，同时启用联系人(供古智调用接口)
	 * 启用：1，禁用：2
	 */
	@Override
	public void openFlag(Long userAccountId) {
		UserAccount userAccount = userManagementService.findUserAcountByUserAcountId(userAccountId);
		Long userInfoId = userAccount.getUserInfo().getUserInfoId();
		Long contactId = findContactByUserInfoId(userInfoId).getContactId();
		if(userAccount.getUserAccountIsEnabled()){
			Contact contact = getContactById(contactId);
			contact.setContactUseFlag(Contact.CONTACT_ENABLE);
		}
	}
	
	/**
	 * 将汉字转换为全拼
	 * 
	 * @param src
	 * @return String
	 */
	private String getPinYin(String src) {
		char[] t1 = null;
		t1 = src.toCharArray();
		String[] t2 = new String[t1.length];
		HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
		t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		t3.setVCharType(HanyuPinyinVCharType.WITH_V);
		String t4 = "";
		int t0 = t1.length;
		try {
			for (int i = 0; i < t0; i++) {
				if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
					t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
					t4 += t2[0];
				} else {
					t4 += Character.toString(t1[i]);
				}
			}
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			e.printStackTrace();
		}
		return t4;
	}

	/**
	 * 通过ID得到Contact实体
	 */
	@SuppressWarnings("unchecked")
	public Contact getContactById(Long contactId) {

		Contact contact = null;

		String hql = "from Contact c where c.contactId = ?";
		List<Contact> list = hibernateEntityDao.find(hql, contactId);
		if (list != null && list.size() > 0) {
			contact = list.get(0);
		}

		return contact;
	}

	/**
	 * 通过IDs得到Contact实体集
	 */
	@SuppressWarnings("unchecked")
	public List<Contact> getContactByIds(Long[] contactIds) {
		List<Contact> list = new ArrayList<Contact>();

		if (contactIds != null && contactIds.length > 0) {
			list = hibernateEntityDao.createQuery(
					"from Contact c where c.contactId in (:a)")
					.setParameterList("a", contactIds).list();
		}
		return list;
	}

	
	/**
	 * 根据用户ID得到联系人ID
	 */
	@Override
	@SuppressWarnings("unchecked")
	public Contact findContactByUserInfoId(Long userInfoId) {
		Contact contact = new Contact();
		String hql = "from Contact c where c.userInfoId=?";
		List<Contact> list = hibernateEntityDao.find(hql, userInfoId);
		if (list.size() != 0) {
			contact = list.get(0);
			return contact;
		}
		return contact ;
	}

}
